<template>
  <div class="app-container">
    <!-- 顶部操作栏 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="searchForm.monitorName" placeholder="监测量名称" clearable @clear="handleSearch" />
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.monitorType" placeholder="监测量类型" clearable @change="handleSearch">
            <el-option v-for="item in monitorTypeOptions" :key="item.monitoringQuantityTypeId"
              :label="item.monitoringQuantityTypeName" :value="item.monitoringQuantityTypeId" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="searchForm.siteAdminId" placeholder="选择站点" style="width: 100%" @change="handleSearch">
            <el-option v-for="item in siteList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-col>
        <el-col :span="10" class="text-right">
          <el-button type="primary" @click="handleSearch" icon="search">
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 监测量表格 -->
    <el-card class="mt-1">
      <el-button type="primary" @click="showCreateDialog">
        <el-icon>
          <Plus />
        </el-icon>
        新增
      </el-button>
      <el-table v-loading="loading" :data="tableData" border align="center" class="monitoring-table mt-2">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="monitorName" label="监测量名称" align="center" />
        <el-table-column prop="monitorCode" label="监测量编码" align="center" />
        <el-table-column prop="monitorUnit" label="单位" align="center" />
        <el-table-column prop="monitorType" label="监测量类型" align="center">
          <template #default="{ row }">
            <el-tag>{{ getName(monitorTypeOptions, row.monitorType, 'monitoringQuantityTypeId',
              'monitoringQuantityTypeName') }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="siteAdminId" label="站点" align="center">
          <template #default="{ row }">
            <el-tag>{{ getName(siteList, row.siteAdminId, 'id', 'name') }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="warningStatus" label="预警" align="center">
          <template #default="{ row }">
            <el-tag :type="row.warningStatus == 0 ? 'success' : 'danger'">{{ row.warningStatus == 0 ? '开启' : '关闭'
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="量程范围" align="center">
          <template #default="{ row }">
            {{ row.rangeMin }} ~ {{ row.rangeMax }}
          </template>
        </el-table-column>
        <el-table-column label="报警阈值" align="center">
          <template #default="{ row }">
            {{ row.alarmMin || '-' }} ~ {{ row.alarmMax || '-' }}
          </template>
        </el-table-column>
        <!-- 映射 -->
        <el-table-column label="设备类型" align="center">
          <template #default="{ row }">
            {{deviceTypeList.find(item => item.value === row.typeId)?.label || row.typeId}}
          </template>
        </el-table-column>
        <!-- 映射 -->
        <el-table-column label="设备" align="center" prop="deviceName" />
        <el-table-column label="状态" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 0 ? 'success' : 'danger'">
              {{ row.status === 0 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="center" />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="text" @click="showEditDialog(row)">编辑</el-button>
            <el-button type="text" @click="handleDelete(row.monitorId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination class="mt-2" v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="`${isEditMode ? '编辑' : '新增'}监测量`" width="600px"
      @closed="handleDialogClosed">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="设备类型" prop="typeId">
          <el-select v-model="formData.typeId" placeholder="设备类型" @change="getDeviceList">
            <el-option v-for="item in deviceTypeList" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择设备" prop="deviceId">
          <el-select v-model="formData.deviceId" placeholder="设备类型">
            <el-option v-for="item in deviceList" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="监测量名称" prop="monitorName">
          <el-input v-model="formData.monitorName" placeholder="请输入监测量名称" />
        </el-form-item>
        <el-form-item label="监测量编码" prop="monitorCode" class="inline-input-btn">
          <el-input v-model="formData.monitorCode" placeholder="请输入监测量编码" disabled />
          <!-- 点击生成按钮时，校验 typeId、deviceId、monitorType，校验不通过不执行现在方法内的代码-->
          <el-button type="primary" @click="getMonitorCode">生成</el-button>
        </el-form-item>
        <el-form-item label="监测量类型" prop="monitorType">
          <el-select v-model="formData.monitorType" placeholder="请选择监测量类型" style="width: 100%" @change="getmonitorUnit">
            <el-option v-for="item in monitorTypeOptions" :key="item.monitoringQuantityTypeId"
              :label="item.monitoringQuantityTypeName" :value="item.monitoringQuantityTypeId + ''" />
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="monitorUnit">
          <el-input v-model="formData.monitorUnit" placeholder="请输入单位" />
        </el-form-item>

        <el-form-item label="量程下限" prop="rangeMin">
          <el-input-number v-model="formData.rangeMin" placeholder="请输入量程下限" :min="0" :precision="2"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="量程上限" prop="rangeMax">
          <el-input-number v-model="formData.rangeMax" placeholder="请输入量程上限" :min="formData.rangeMin || 0"
            :precision="2" style="width: 100%" />
        </el-form-item>
        <el-form-item label="报警下限" prop="alarmMin">
          <el-input-number v-model="formData.alarmMin" placeholder="请输入报警下限" :min="formData.rangeMin || 0"
            :max="formData.rangeMax || Infinity" :precision="2" style="width: 100%" />
        </el-form-item>
        <el-form-item label="报警上限" prop="alarmMax">
          <el-input-number v-model="formData.alarmMax" placeholder="请输入报警上限"
            :min="formData.alarmMin || formData.rangeMin || 0" :max="formData.rangeMax || Infinity" :precision="2"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="选择站点" prop="siteAdminId">
          <el-select v-model="formData.siteAdminId" placeholder="选择站点" style="width: 100%">
            <el-option v-for="item in siteList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="预警" prop="warningStatus">
          <el-select v-model="formData.warningStatus" placeholder="是否开启预警" style="width: 100%">
            <el-option label="开启" :value="0" />
            <el-option label="关闭" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="启用" :value="0"></el-option>
            <el-option label="禁用" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请输入备注信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Plus, Upload, Download, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as api from '@/api/park/monitor/lib'
const getmonitorUnit = () => {
  formData.monitorUnit = monitorTypeOptions.value.find(item => item.monitoringQuantityTypeId == formData.monitorType)?.unit
}
const getMonitorCode = () => {
  // 1. 校验设备类型（typeId）
  if (!formData.typeId) {
    ElMessage.warning('请先选择设备类型');
    return;
  }
  // 2. 校验设备（deviceId）
  if (!formData.deviceId) {
    ElMessage.warning('请先选择设备');
    return;
  }
  // 3. 校验监测量类型（monitorType）
  if (!formData.monitorType) {
    ElMessage.warning('请先选择监测量类型');
    return;
  }
  const one = deviceList.value.find(item => item.value == formData.deviceId)?.extend
  const two = monitorTypeOptions.value.find(item => item.monitoringQuantityTypeId == formData.monitorType)?.filed
  const three = deviceList.value.find(item => item.value == formData.deviceId)?.value
  formData.monitorCode = `${two}_${one}_${three}`
}
// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  monitorName: undefined,
  monitorCode: undefined,
  monitorType: undefined,
  valueType: undefined
})

// 搜索表单
const searchForm = reactive({
  monitorName: undefined,
  monitorCode: undefined,
  monitorType: undefined,
  valueType: undefined
})

// 表单数据
const formData = reactive({
  monitorId: undefined,
  monitorName: '',
  monitorCode: '',
  monitorUnit: '',
  monitorType: undefined,
  valueType: undefined,
  rangeMin: undefined,
  rangeMax: undefined,
  alarmMin: undefined,
  alarmMax: undefined,
  status: undefined,
  typeId: undefined,
  deviceId: undefined,
  remark: ''
})

const deviceTypeList = ref()
const getDataList = async () => {
  const deviceTypeRes = await api.getDeviceTypeList()
  deviceTypeList.value = deviceTypeRes.data.map(item => ({
    label: item.name,
    value: item.id
  }));
}
const deviceList = ref()
const getDeviceList = async (typeId) => {
  formData.deviceId = ''
  const deviceRes = await api.getDeviceList(typeId)
  deviceList.value = deviceRes.data.map(item => ({
    label: item.name,
    value: item.id,
    extend: item.extend
  }));
}

// 表单验证规则
const rules = reactive({
  monitorName: [
    { required: true, message: '监测量名称不能为空', trigger: 'blur' }
  ],
  monitorCode: [
    { required: true, message: '监测量编码不能为空', trigger: 'blur' }
  ],
  monitorUnit: [
    { required: true, message: '单位不能为空', trigger: 'change' }
  ],
  monitorType: [
    { required: true, message: '请选择监测量类型', trigger: 'change' }
  ],
  valueType: [
    { required: true, message: '请选择值类型', trigger: 'change' }
  ],
  rangeMin: [
    { required: true, message: '量程下限不能为空', trigger: 'blur' },
    { type: 'number', min: 0, message: '量程下限必须大于等于0' }
  ],
  typeId: [
    { required: true, message: '请选择设备类型', trigger: 'blur' }
  ],
  deviceId: [
    { required: true, message: '请选择设备', trigger: 'blur' }
  ],
  rangeMax: [
    { required: true, message: '量程上限不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value <= formData.rangeMin) {
          callback(new Error('量程上限必须大于量程下限'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 表格数据
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 下拉选项
const monitorTypeOptions = ref([])
const valueTypeOptions = ref([])

// 对话框控制
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)

// 导入相关
const importDialogVisible = ref(false)
const fileList = ref([])
const updateSupport = ref(false)
const uploadRef = ref(null)

const siteList = ref([]);
const getSiteList = async () => {
  const { data } = await api.getSiteList();
  siteList.value = data;
}

// 初始化数据
onMounted(() => {
  getList()
  getDicts()
  getDataList()
  getSiteList();
})

// 获取字典数据
const getDicts = async () => {
  try {
    const [monitorTypes, valueTypes] = await Promise.all([
      api.getMonitoringTypeList(),
      api.getValueTypeList()
    ])
    monitorTypeOptions.value = monitorTypes.data
    valueTypeOptions.value = valueTypes.data
  } catch (error) {
    console.error('获取字典数据失败:', error)
  }
}

// 获取列表数据
const getList = async () => {
  try {
    loading.value = true
    const res = await api.getMonitoringLibraryList(queryParams)
    tableData.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('获取列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    ...searchForm
  })
  getList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    monitorName: undefined,
    monitorCode: undefined,
    monitorType: undefined,
    valueType: undefined,
    siteAdminId:''
  })
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

// 当前页变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

// 显示新增对话框
const showCreateDialog = () => {
  isEditMode.value = false
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row) => {
  getDeviceList(row.typeId)
  isEditMode.value = true
  dialogVisible.value = true
  Object.assign(formData, row)
}

// 对话框关闭
const handleDialogClosed = () => {
  formRef.value?.resetFields()
  // formData.monitorId = undefined
  // formData.monitorName = ''
  // formData.monitorCode = ''
  // formData.monitorUnit = ''
  // formData.monitorType = undefined
  // formData.valueType = undefined
  // formData.rangeMin = undefined
  // formData.rangeMax = undefined
  // formData.alarmMin = undefined
  // formData.alarmMax = undefined
  // formData.status = undefined
  // formData.typeId = undefined
  // formData.deviceId = undefined
  // formData.remark = ''
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      if (isEditMode.value) {
        await api.updateMonitoringLibrary(formData)
        ElMessage.success('修改成功')
      } else {
        await api.addMonitoringLibrary(formData)
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false
      getList()
    } catch (error) {
      console.error('提交失败:', error)
    }
  })
}

// 删除
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除这条记录吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await api.deleteMonitoringLibrary(id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

// 导出
const handleExport = async () => {
  try {
    const params = {
      ...queryParams,
      pageNum: undefined,
      pageSize: undefined
    }
    const res = await api.exportMonitoringLibrary(params)

    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([res]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', '监测量库数据.xlsx')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('导出失败:', error)
  }
}

// 导入
const handleImport = () => {
  importDialogVisible.value = true
  fileList.value = []
  updateSupport.value = false
}

// 文件变化
const handleFileChange = (file) => {
  fileList.value = [file]
}

// 文件超出限制
const handleExceed = () => {
  ElMessage.warning('每次只能上传一个文件')
}

// 提交导入
const submitImport = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请先选择文件')
    return
  }

  try {
    const formData = new FormData()
    formData.append('file', fileList.value[0].raw)
    formData.append('updateSupport', updateSupport.value)

    const res = await api.importMonitoringLibrary(formData)
    ElMessage.success('导入成功')
    importDialogVisible.value = false
    getList()
  } catch (error) {
    console.error('导入失败:', error)
  }
}
</script>

<style scoped>
.upload-demo {
  margin-bottom: 20px;
}
</style>

<style scoped>
/* 针对自定义类名的表单项，修改内容区域布局 */
.inline-input-btn .el-form-item__content {
  display: flex;
  /* 开启Flex布局 */
  align-items: center;
  /* 垂直居中对齐 */
  gap: 10px;
  /* 输入框和按钮之间的间距（可选） */
}

/* 让输入框占满剩余宽度（避免被按钮挤压） */
.inline-input-btn .el-input {
  flex: 1;
  /* 自动填充剩余空间 */
}
</style>